package com.kun.controller;

import com.kun.mapper.HandleOrderMapper;
import com.kun.mapper.OrderMapper;
import com.kun.mapper.UserMapper;
import com.kun.pojo.HandleOrder;
import com.kun.pojo.Order;
import com.kun.pojo.User;
import com.kun.service.HandleOrderService;
import com.kun.service.OrderService;
import com.kun.service.UserService;
import com.kun.utils.VertifyCode.CheckCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Version:v1.0
 * @Author: 鲁坤
 * @Date: 2021-03-15
 * @ClassName: UserController
 * @Description: 相关功能额控制器
 */
@Controller
public class UserController {
//    @Autowired
//    private UserMapper userMapper;
    @Autowired
    private UserService userService;
//    @Autowired
//    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
//    @Autowired
//    private HandleOrderMapper handleOrderMapper;
    @Autowired
    private HandleOrderService handleOrderService;
    /*-----------------------------------------注册相关-----------------------------------------*/
    //跳转到注册页面
    @RequestMapping("/register")
    public String UserRegister(){
        return "register";
    }
    @RequestMapping("/registerinfo")
    public String RegisterInfo(Model model,
                               @RequestParam("username")String username,
                               @RequestParam("password")String password,
                               @RequestParam("password2")String password2,
                               @RequestParam("email")String email,
                               HttpServletResponse response) throws IOException {
        //User user = userMapper.queryUserByUsername(username);             //不用缓存
        User user = userService.queryUserByUsername(username);              //使用缓存
        if(user!=null){//用户名已被占用
            model.addAttribute("msg","此用户名已被占用，请换一个");
            model.addAttribute("username",username);
            model.addAttribute("email",email);
            return "register";
        }else{
            if(!password.equals(password2)){//两次密码不一致
                model.addAttribute("msg","密码不一致，请重新设置");
                model.addAttribute("username",username);
                model.addAttribute("email",email);
                model.addAttribute("password",password);
                return "register";
            }else {
                User user1 = new User(username, password, email);
                //userMapper.addUser(user1);//追加用户 待审核                  //不用缓存
                userService.addUser(user1);
                PrintWriter writer = response.getWriter();
                response.setContentType("text/html;charset=UTF-8");
                writer.print("<script>alert('已注册，请及时查收您的邮箱');</script>");
                writer.flush();
                return "login";
            }
        }

    }
    /*-----------------------------------------登陆相关-----------------------------------------*/
    //跳转到登录界面
    @RequestMapping("/login")
    public String UserLogin(HttpSession session){
        session.invalidate();
        return "login";
    }
    @RequestMapping("/user_login")
    public String AdminLogin(@RequestParam("username")String username,
                             @RequestParam("password")String password,
                             @RequestParam("thevertifycode")String thevertifycode,
                             HttpSession session,
                             Model model){
        //User user = userMapper.queryUserByUsername(username);                 //不用缓存
        User user = userService.queryUserByUsername(username);                  //使用缓存
        if(user==null){//首先判断是否存在该用户
            model.addAttribute("msg","用户名错误，请重试");
            return "login";
        }else{//其次 判断密码的正确性
            if(!password.equals(user.getPassword())){//密码错误
                model.addAttribute("username",username);
                model.addAttribute("msg","密码错误，请重试");
                return "login";
            }else{//密码正确
                if(!thevertifycode.equals(session.getAttribute("vertifycode"))){//判断验证码
                    model.addAttribute("username",username);
                    model.addAttribute("password",password);
                    model.addAttribute("msg","验证码错误，请重试");
                    return "login";
                }else {//验证码正确
                    if(user.getLstatus()==0){
                        model.addAttribute("username",username);
                        model.addAttribute("password",password);
                        model.addAttribute("msg","该用户为劣迹用户，已被禁用");
                        return "login";
                    }else{
                        session.setAttribute("trueuser",user);
                        return "index";
                    }

                }
            }
        }

    }
    //验证码功能
    @RequestMapping("/vertifycode")
    public void GetVertifyCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
        HttpSession session = request.getSession();
        CheckCode checkCode = new CheckCode(null,4,20,16);
        Object[] objects = checkCode.createImage();
        //验证码存入session
        session.setAttribute("vertifycode",String.valueOf(objects[0]));
        //将图片存入session
        BufferedImage image = (BufferedImage) objects[1];
        response.setContentType("img/png");
        ServletOutputStream os = response.getOutputStream();
        ImageIO.write(image,"png",os);
    }
    @RequestMapping("/logout")
    public String Logout(HttpSession session){
        Timestamp logouttime = new Timestamp(System.currentTimeMillis());
        User trueuser = (User) session.getAttribute("trueuser");
        trueuser.setLogintime(logouttime);
        //userMapper.updateUser(trueuser);              //不用缓存
        userService.updateUser(trueuser);               //使用缓存
        session.invalidate();
        return "login";
    }
    /*-----------------------------------------页面跳转相关-----------------------------------------*/
    //跳转至首页
    @RequestMapping("/index")
    public String UserIndex(){
        return "index";
    }
    //跳转至工单创建页
    @RequestMapping("/create_order")
    public String CreateOrder(){
        return "user_order";
    }
    //跳转至正在处理工单
    @RequestMapping("/order_in_handle")
    public String OrderInHandle(Model model,
                                HttpSession session){
        User trueuser = (User)session.getAttribute("trueuser");
        //定义map 用来存放用户id和工单状态ostatus
        Map<String, Integer> map = new HashMap<String,Integer>();
        map.put("uid",trueuser.getUid());
        map.put("ostatus",1);
        //List<Order> orders = orderMapper.getOrderByUserAndStatus(map);        //不用缓存
        List<Order> orders = orderService.getOrderByUserAndStatus(map);         //使用缓存
        model.addAttribute("orders",orders);
        return "order_in_handle";
    }
    //跳转至历史工单
    @RequestMapping("/order_history")
    public String OrderHistory(Model model,
                               HttpSession session){
        User trueuser = (User)session.getAttribute("trueuser");
        //定义map 用来存放用户id和工单状态ostatus
        Map<String, Integer> map = new HashMap<String,Integer>();
        map.put("uid",trueuser.getUid());
        map.put("ostatus",0);
        //List<Order> orders = orderMapper.getOrderByUserAndStatus(map);        //不用缓存
        List<Order> orders = orderService.getOrderByUserAndStatus(map);         //使用缓存
        model.addAttribute("orders",orders);
        return "history_order";
    }

    /*-----------------------------------------信息修改相关-----------------------------------------*/
    @RequestMapping("/user_profile")
    public String UserProfile(Model model,
                              HttpSession session){
        User trueuser = (User)session.getAttribute("trueuser");
        model.addAttribute("theuser",trueuser);
        return "user_profile";
    }
    @RequestMapping("/update_user")
    public String UpdateUser(Model model,
                             @RequestParam("age") int age,
                             @RequestParam("address")String address,
                             @RequestParam("gender")String gender,
                             @RequestParam("photo")String photo,
                             HttpSession session){
        User trueuser = (User)session.getAttribute("trueuser");
        trueuser.SetTheRestInfo(age,address,gender,photo);
        //userMapper.updateUser(trueuser);                  //不用缓存
        userService.updateUser(trueuser);                   //使用缓存
        session.setAttribute("trueuser",trueuser);
        model.addAttribute("theuser",trueuser);
        return "user_profile";
    }
    /*-----------------------------------------工单创建相关-----------------------------------------*/
    @RequestMapping("/create_the_sheet")
    public String CreateTheSheet(Model model,
                                 HttpServletResponse response,
                                 HttpSession session,
                                 @RequestParam(value = "title") String title,
                                 @RequestParam("question")String question,
                                 @RequestParam("orderlevel")int orderlevel,
                                 @RequestParam(value = "ordertype")String ordertype) throws IOException {
        if(title.equals("")){
            model.addAttribute("msg","您的标题为空");
            return "user_order";
        }else{
            if(question.equals("")){
                model.addAttribute("msg","您的问题不明确");
                model.addAttribute("title",title);
                return "user_order";
            }else {

                User trueuser = (User)session.getAttribute("trueuser");

                Timestamp createtime = new Timestamp(System.currentTimeMillis());
                Order order = new Order(trueuser.getUid(), ordertype, title, question, orderlevel, createtime);
                //orderMapper.addOrder(order);                      //不用缓存
                orderService.addOrder(order);                       //使用缓存
                PrintWriter writer = response.getWriter();
                response.setContentType("text/html;charset=UTF-8");
                writer.print("<script>alert('创建成功');</script>");
                writer.flush();
                System.out.println(createtime);
                return "index";
            }
        }
    }
    /*-----------------------------------------查看工单相关-----------------------------------------*/
    //结束工单
    @RequestMapping("/kill_order/{oid}")
    public String KillOrder(Model model,
                            @PathVariable("oid") int oid,
                            @RequestParam("changeostatus")int changeostatus){
        //Order order = orderMapper.getOrderByOid(oid);             //不用缓存
        Order order = orderService.getOrderByOid(oid);              //使用缓存
        Timestamp endtime = new Timestamp(System.currentTimeMillis());
        order.setOstatus((order.getOstatus()+changeostatus)%2);
        order.setEndtime(endtime);
        //orderMapper.updateOrderStatus(order);                     //不用缓存
        orderService.updateOrderStatus(order);                      //使用缓存
        model.addAttribute("oid",oid);
        return "user_order_comment";
        //return "redirect:/index";
    }
    //工单评价
    @RequestMapping("/submit_comment")
    public  String SubminComment(@RequestParam("oid")int oid,
                                 @RequestParam("commentscore")float comment_score,
                                 @RequestParam("comment")String comment,
                                 Model model){
        model.addAttribute("oid",oid);
        if(comment_score<=100.0&&comment_score>=0.0){
            if(comment==null||comment.equals("")){
                model.addAttribute("commentscore",comment_score);
                model.addAttribute("msg","评论为空");
                return "user_order_comment";
            }else{
                //Order order = orderMapper.getOrderByOid(oid);         //不用缓存
                Order order = orderService.getOrderByOid(oid);          //使用缓存
                order.setCommentscore(comment_score);
                order.setComment(comment);
                //orderMapper.updateOrderStatus(order);                 //不用缓存
                orderService.updateOrderStatus(order);                  //使用缓存
                return "redirect:/index";
            }
        }else{
            model.addAttribute("msg","评分不合法");
            return "user_order_comment";
        }

    }
    //跳转到答复工单
    //有两个入口可以调用这个方法
    @RequestMapping("/order_in_handle/{oid}")
    public String DealOrder(@PathVariable("oid")int oid,
                            HttpSession session,
                            Model model,
                            @RequestParam(value = "user_reply_copy",required = false)String user_reply_copy){
        session.setAttribute("usernowoid",oid);
        //如何将数据展示出来？？？
        //Order order = orderMapper.getOrderByOid(oid);                 //不用缓存
        Order order = orderService.getOrderByOid(oid);                  //用缓存

        //List<HandleOrder> handleOrders = handleOrderMapper.queryAnswerByOid(oid);     //不用缓存
        List<HandleOrder> handleOrders = handleOrderService.queryAnswerByOid(oid);      //用缓存
        model.addAttribute("userhandleorder",handleOrders);
        model.addAttribute("userorder",order);

        //System.out.println(user_reply_copy);
        if(user_reply_copy!=null&&!user_reply_copy.equals("")){
            session.setAttribute("user_reply",user_reply_copy);
        }
        //查找数据，放到list中
        return "user_handle_order_detail";
    }
    //消息回复
    @RequestMapping("/user_answer")
    public String UserAnswer(Model model,
                             HttpSession session,
                             @RequestParam("user_reply")String user_reply){
        int oid = (int)session.getAttribute("usernowoid");//获取当前表单的id
        //回复不为空 才能回复成功
        if(user_reply!=null&&!user_reply.equals("")){
            User trueuser = (User) session.getAttribute("trueuser");
            String username = trueuser.getUsername();
            Timestamp replytime = new Timestamp(System.currentTimeMillis());
            HandleOrder handleOrder = new HandleOrder(oid, username, 0, user_reply, replytime);
            //handleOrderMapper.addAnswer(handleOrder);             //不用缓存
            handleOrderService.addAnswer(handleOrder);              //用缓存
            session.removeAttribute("user_reply");
        }

        //Order order = orderMapper.getOrderByOid(oid);             //不用缓存
        Order order = orderService.getOrderByOid(oid);              //用缓存

        //List<HandleOrder> handleOrders = handleOrderMapper.queryAnswerByOid(oid);         //不用缓存
        List<HandleOrder> handleOrders = handleOrderService.queryAnswerByOid(oid);          //用缓存
        model.addAttribute("userhandleorder",handleOrders);
        model.addAttribute("userorder",order);
        //model.addAttribute("user_reply",user_reply);
        return "user_handle_order_detail";
    }
    /*-----------------------------------------工单详情相关-----------------------------------------*/
    @RequestMapping("/user_order_detail/{oid}")
    public String UserOrderDetail(Model model,
                                  @PathVariable("oid")int oid){
        //Order order = orderMapper.getOrderByOid(oid);                         //不用缓存
        Order order = orderService.getOrderByOid(oid);                          //用缓存

        //List<HandleOrder> handleOrders = handleOrderMapper.queryAnswerByOid(oid);         //不用缓存
        List<HandleOrder> handleOrders = handleOrderService.queryAnswerByOid(oid);          //用缓存
        model.addAttribute("userhandleorder",handleOrders);
        model.addAttribute("userorder",order);

        return "user_order_detail";
    }

}
